local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
local pairs = pairs
local type = type
package.path = "/opt/xyitech/jieyan-backend-production/?.lua;;"
package.cpath = "/opt/xyitech/jieyan-backend-production/?.so;;"
local xml = require "LuaXml"
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)
_VERSION = '0.1'


function search(user, args)
    local id = args.id
    local db = conf.get_mysql()
    local res = nil
    local count = nil
    local sql = "SELECT * from `area` where id in (" ..  table.concat(user.aids, ",") .. ")"
    if id then
        sql = sql .. " AND id = " .. id
    end
    ngx.log(ngx.ERR, "-----THIS IS DEBUG---")
    ngx.log(ngx.ERR, sql)
    res = db:query(sql)
    if not res then
        ngx.print(json.encode({
            err = 0,
            msg = {}
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end

function updateWeather()
    local db = conf.get_mysql()
    local http = require("http")
    local sql = "SELECT id, cityId, py_name from `area`"
    local res = db:query(sql) 
    local data = {}
    for k,v in pairs(res) do
        -- ngx.log(ngx.ERR, v.py_name)
        if v.py_name and v.py_name ~= "" then
            local ok, code, _, _, body  = http:request {
                url = "http://flash.weather.com.cn/wmaps/xml/" .. v.py_name ..".xml",
                timeout = 6000,
                method = "GET",
            }
            -- ngx.log(ngx.ERR, json.encode(body))
            if code == 200 and body then
                local resp = xml.eval(body)
                local tag = resp:find(v.py_name)
                for k,v in pairs(tag) do
                    -- data[]
                    if type(v) == "table" then
                        ngx.log(ngx.ERR, v.url)
                        data[v.url] = v
                    end
                end
            end
        end
    end
    ngx.log(ngx.ERR, json.encode(data))
    for k,v in pairs(res) do
        local vals = {}
        if v.cityId and v.cityId ~= 0 then
            local weather, wind = "", ""
            local city = data[v.cityId..""]
            if city then
                vals[#vals + 1] = "weather = " .. ngx.quote_sql_str(city.stateDetailed)
                vals[#vals + 1] = "wind = " .. ngx.quote_sql_str(city.windDir .. " " .. city.windPower)
                local res, err = db:query("UPDATE area SET " .. table.concat(vals, ",") .. " WHERE id = " .. v.id)
            end
            -- ngx.log(ngx.ERR, json.encode(res))
            -- ngx.log(ngx.ERR, json.encode(err))
        end
    end
    ngx.print(json.encode({
            err = 0,
            msg = ""
    }))
    ngx.exit(200)
end

function default(args)
    if args.action == 'search' then
        local user = conf.parse_token(args, "area")
        search(user, args)
    elseif args.action == 'updateWeather' then
        updateWeather()
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
